package com.jbh.wanandroidkotlin.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.jbh.apilibrary.AppData
import com.jbh.apilibrary.bean.BannerResultBean
import com.jbh.apilibrary.bean.IndexArticleListBean
import com.jbh.apilibrary.bean.IndexArticleListResult
import com.jbh.apilibrary.i.ApiCallBack
import com.jbh.wanandroidkotlin.R
import com.jbh.wanandroidkotlin.activity.CommonActivity
import com.jbh.wanandroidkotlin.activity.LoginActivity
import com.jbh.wanandroidkotlin.manager.AppActivityManager
import com.jbh.wanandroidkotlin.manager.UserInfoManager
import com.jbh.wanandroidkotlin.util.WEB_LINK
import com.jbh.wanandroidkotlin.util.data
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.layout.header.ClassicsHeader
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener
import com.stx.xhb.xbanner.XBanner
import com.stx.xhb.xbanner.entity.SimpleBannerInfo
import com.stx.xhb.xbanner.transformers.Transformer
import kotlinx.android.synthetic.main.activity_favorite_list.*
import kotlinx.android.synthetic.main.fragment_index.*
import kotlinx.android.synthetic.main.fragment_index.header
import kotlinx.android.synthetic.main.fragment_index.second_floor_content
import com.chad.library.adapter.base.BaseQuickAdapter as BaseQuickAdapter

private const val ARG_PARAM1 = "param1"

class IndexFragment : Fragment() {

    private var param1: String? = null
    /**
     * 记录上拉还是下拉
     */
    private var isPullRefresh = true
    /**
     * 当前页码
     */
    private var page = 0
    /**
     * 文章的总页数
     *
     */
    private var pageAll = 0;
    /**
     * 文章列表
     *
     */
    private val listContent  = mutableListOf<IndexArticleListBean>()

    private var contentListAdapter : ContentListAdapter ?= null

    private  var mSmartRefreshLayout : SmartRefreshLayout ?= null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_index, container, false)
    }


    companion object {
        @JvmStatic
        fun newInstance(param1: String ="") = IndexFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                }
            }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        second_floor_content = view.findViewById(R.id.second_floor_content)
        mSmartRefreshLayout = view.findViewById(R.id.mSmartRefreshLayout);
        mRecyclerView.apply {
            val l = LinearLayoutManager(activity)
            l.orientation = LinearLayoutManager.VERTICAL
            layoutManager = l
            contentListAdapter = ContentListAdapter(listContent)
            adapter = contentListAdapter
        }
        contentListAdapter?.setOnItemClickListener { adapter, view, position ->
            val b = Bundle();
            b.putString(WEB_LINK,listContent[position].link)
            startActivity(Intent(activity,CommonActivity::class.java).putExtra(data, b))
        }
        initRefresh()
    }



    /**
     * 获取首页banner
     */
    private fun bannerTask(){
        AppData.instance().bannerTask(object : ApiCallBack<List<BannerResultBean>> {
            override fun success(data: List<BannerResultBean>) {
                println("[bannerTask] - > success = ${Gson().toJson(data)}")
                activity?.runOnUiThread {
                    initBanner(data)
                }
            }

            override fun error(error: String) {
                println("[bannerTask] - > error = $error")
            }
        })
    }


    private fun initBanner(list: List<BannerResultBean>) {
        val  l = mutableListOf<BannerDataBean>()
        for (it in list){
            l.add(BannerDataBean(it.desc,it.id,it.imagePath,it.isVisible,it.order,it.title,it.type,it.url))
        }
        mXBanner.run {
            for (it in list){
                l.add(BannerDataBean(it.desc,it.id,it.imagePath,it.isVisible,it.order,it.title,it.type,it.url))
            }
            mXBanner.setBannerData(R.layout.common_image_view,l)
            mXBanner.setPageTransformer(Transformer.Default)
            mXBanner.loadImage(LoadImage(l))
        }
        
        mXBanner.setOnItemClickListener { banner, model, view, position ->
            val b = Bundle();
            b.putString(WEB_LINK,list[position].url)
            startActivity(Intent(activity,CommonActivity::class.java).putExtra(data, b))
        }
    }




    inner class BannerDataBean(val desc:String,
                         val id:Int,
                         val imagePath:String,
                         val isVisible:Int,
                         val order:Int,
                         val title:String,
                         val type:Int,
                         val url:String):SimpleBannerInfo(){
        override fun getXBannerUrl(): Any {
            return title ;
        }
    }




    inner class LoadImage(private val l:List<BannerDataBean>):XBanner.XBannerAdapter{
        override fun loadBanner(banner: XBanner?, model: Any?, view: View?, position: Int) {
            val  img = view as ImageView
            img.scaleType  = ImageView.ScaleType.CENTER_CROP
            activity?.let {
                Glide.with(it.applicationContext)
                    .asBitmap()
                    .load(l[position].imagePath)
                    .into(img)
            }
        }
    }



    private var second_floor_content :View?=null

    private fun initRefresh(){
        mSmartRefreshLayout?.apply {
            autoRefresh()

            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(RefreshHead())
            setOnLoadMoreListener(RefreshFoot())

            setOnMultiPurposeListener(object : SimpleMultiPurposeListener() {
                override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {
                    super.onStateChanged(refreshLayout, oldState, newState)
                    if (oldState == RefreshState.TwoLevel) {
                        mActionBarView.setTitle("首页")
                        second_floor_content?.let { it.animate().alpha(0f).duration = 1000}
                    }
                }
            })
        }


        /*二楼*/
        header!!.setOnTwoLevelListener {
            second_floor_content?.let {
                mActionBarView.setTitle("二楼广场")
                it .animate().alpha(1f).duration = 2000
            }
            true
        }
    }



    inner class RefreshFoot : OnLoadMoreListener {

        override fun onLoadMore(refreshLayout: RefreshLayout) {
            isPullRefresh = false
            page ++ ;
            if (pageAll >= page){
                indexArticleTask();
            }else{
                mSmartRefreshLayout?.finishLoadMore(0, true, true)
            }
        }
    }




    inner class RefreshHead : OnRefreshListener {

        override fun onRefresh(refreshLayout: RefreshLayout) {
            bannerTask()

            isPullRefresh = true
            page = 0;
            listContent.clear()
            indexArticleTask();
        }
    }




    /**
     * 获取首页列表文章
     */
    private fun indexArticleTask(){
        AppData.instance().indexArticleTask(page, object : ApiCallBack<IndexArticleListResult> {
            override fun success(data: IndexArticleListResult) {
                activity?.runOnUiThread {
                    pageAll = data.pageCount
                    println("[indexArticleTask] - > success = $pageAll")
                    listContent.addAll(data.datas)
                    contentListAdapter ?.notifyDataSetChanged()
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, false)
                    }
                }
            }

            override fun error(error: String) {
                println("[indexArticleTask] - > error = $error")
                activity?.runOnUiThread {
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, true)
                    }
                }
            }
        })
    }



    inner class ContentListAdapter(l : List<IndexArticleListBean>) :
        BaseQuickAdapter<IndexArticleListBean,BaseViewHolder>(R.layout.item_index_layout,l){
        override fun convert(helper: BaseViewHolder, item: IndexArticleListBean) {
            helper.setText(R.id.title,item.title)
                .setText(R.id.tv_subtitle,item.shareUser)
        }
    }




}



